package com.cskaoyan.service;

import com.cskaoyan.bean.zhao_order_bean.BasePageData;
import com.cskaoyan.bean.Role;
import com.cskaoyan.bean.RoleExample;
import com.cskaoyan.bean.basebean.BaseParam;
import com.cskaoyan.bean.sysmanage.UpdateRoleBo;
import com.cskaoyan.exception.MarketException;
import com.cskaoyan.mapper.RoleMapper;
import com.cskaoyan.utils.MarketPageUtil;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    RoleMapper roleMapper;

    @Override
    public BasePageData queryRoleList(String name, BaseParam baseParam) {
        MarketPageUtil.startPage(baseParam);
        RoleExample example = new RoleExample();
        RoleExample.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        example.setOrderByClause(baseParam.getSort() + " " + baseParam.getOrder());
        List<Role> roles = roleMapper.selectByExample(example);
        return BasePageData.ok(roles);
    }

    @Override
    public Role selectByName(String name) {
        RoleExample example = new RoleExample();
        RoleExample.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(name)) {
            criteria.andNameEqualTo(name);
        }
        List<Role> roles = roleMapper.selectByExample(example);
        return roles.size() == 0 ? null : roles.get(0);
    }

    @SneakyThrows
    @Override
    public Role addRole(String name, String desc) {
        Role role = new Role();
        role.setName(name);
        role.setDesc(desc);
        role.setAddTime(new Date());
        role.setUpdateTime(new Date());
        int insertRows = roleMapper.insertSelective(role);
        if (insertRows != 1) {
            throw new MarketException("添加成员名称失败");
        }

        //添加成员名称成功
        Role addRole = selectByName(name);
        return addRole;
    }

    @Override
    public boolean updateRole(UpdateRoleBo updateRoleBO) {
        Role role = new Role();
        role.setId(updateRoleBO.getId());
        role.setName(updateRoleBO.getName());
        role.setDesc(updateRoleBO.getDesc());
        role.setUpdateTime(new Date());
        int affectRows = roleMapper.updateByPrimaryKey(role);
        return affectRows == 1;
    }

    @Override
    public boolean deleteRoleById(Integer id) {
        int deleteRow = roleMapper.deleteByPrimaryKey(id);
        return deleteRow == 1;
    }
}
